import threading
import time

import numpy as np
import pandas as pd
import streamlit as st
import pymysql
import random
import datetime

from matplotlib import pyplot as plt, image as mpimg
from matplotlib.image import BboxImage
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from matplotlib.transforms import Bbox
from streamlit_echarts import st_echarts

from tags import tags

from matplotlib.patches import PathPatch
from matplotlib.path import Path

st.set_page_config(
    page_title="厄厄杯-线上娱乐赛",
    page_icon="👋",
)

hide_streamlit_style = """
    <style>
        .reportview-container {
            margin-top: -2em;
        }
        #MainMenu {visibility: hidden;}
        .stDeployButton {display:none;}
        footer {visibility: hidden;}
        #stDecoration {display:none;}
    </style>
            """
st.markdown(hide_streamlit_style, unsafe_allow_html=True)


# Streamlit应用程序
st.markdown("<h1 style='text-align: center;'>🎉厄厄杯-线上娱乐赛🎉</h1>", unsafe_allow_html=True)

# 设定目标日期
target_date = datetime.datetime(2024, 2, 5,13,0)

now = datetime.datetime.now()
countdown = target_date - now

# 格式化显示倒计时
days = countdown.days
hours, remainder = divmod(countdown.seconds, 3600)
minutes, seconds = divmod(remainder, 60)

# 创建一个自定义的HTML和CSS样式
badge_html = """
<div style="
    border: 3px solid #B8860B; 
    border-radius: 15px; 
    text-align: center; 
    color: #B8860B; 
    font-size: 24px; 
    padding: 5px; 
    width: 200px;
    margin: auto;">
    测试阶段
</div>
"""
st.markdown(badge_html, unsafe_allow_html=True)

st.markdown("<br>", unsafe_allow_html=True)

MYSQL_HOST = "127.0.0.1"
MYSQL_PORT = 3306
MYSQL_USER = "root"
MYSQL_PASSWORD = "G5v3m5e5!"
MYSQL_DB = "random_tag_ygo"

# 连接MySQL数据库
conn = pymysql.connect(
    host=MYSQL_HOST,
    port=MYSQL_PORT,
    user=MYSQL_USER,
    password=MYSQL_PASSWORD,
    database=MYSQL_DB
)

# 创建游标
cursor = conn.cursor()

# 创建user_data表（如果不存在）
cursor.execute("""
    CREATE TABLE IF NOT EXISTS random_tags (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(255) UNIQUE,
        elements VARCHAR(255),
        verify_code VARCHAR(255),
        created_at DATE DEFAULT (CURRENT_DATE)
    )
""")

# 替换以下 SQL 查询为你要选择的数据
sql_query = 'SELECT elements FROM random_tags'

# 使用pandas的read_sql函数来执行查询并将结果加载到DataFrame
df = pd.read_sql(sql_query, conn)

tag_counter = {k:0 for k in tags}

for index, row in df.iterrows():
    value = row['elements']
    elements = str(value).replace(" ","").split(",")
    for e in elements:
        tag_counter[e] += 1

sorted_dict = dict(sorted(tag_counter.items(), key=lambda item: item[1]))

# plt.rcParams['font.sans-serif'] = ['SimHei']  # 'SimHei' 是一种常用的中文黑体
# plt.rcParams['font.family']='sans-serif'
# plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

top_items = list(sorted_dict.items())[-15:]
echart_pie_data = []
for t in top_items:
    echart_pie_data.append({"name":str(t[0]), "value": str(t[1])})
    # echart_pie_data.append({"name":str(t[0]), "value": str(t[1]),"itemStyle": {"color": {"image": f'http://8.130.89.246:8080/resources/cut_{str(t[0])}.jpg', "repeat": 'repeat' }}})

def render_basic_area_chart():
    options = {
        "tooltip": {
            "trigger": 'item',
            "formatter": '{b}: {c} ({d}%)'
        },
        "series": [
            {
                "type": "pie",
                "data": echart_pie_data,
                "label": {
                    "normal": {
                        "show": True,
                        "formatter": '{b}: {d}%'
                    }
                }
            }
        ],

    }
    st.markdown("<h3 style='text-align: center;'>TOP字段</h3>", unsafe_allow_html=True)
    st_echarts(options=options,height='500px')

xx = []
yy = []
for k,v in sorted_dict.items():
    xx.append(v)
    yy.append(k)
def render_bar_chart():
    option = {
        'tooltip': {
            'trigger': 'axis',
            'axisPointer': {
                'type': 'shadow'
            }
        },
        'legend': {},
        'grid': {
            'left': '3%',
            'right': '4%',
            'bottom': '3%',
            'containLabel': True
        },
        'xAxis': {
            'type': 'value',
            'boundaryGap': [0, 0.01]
        },
        'yAxis': {
            'type': 'category',
            'data': yy
        },
        'series': [
            {
                'type': 'bar',
                'data': xx
            }
        ]
    }
    st.markdown("<h3 style='text-align: center;'>所有字段</h3>", unsafe_allow_html=True)
    st_echarts(options=option,height='1200px')

render_basic_area_chart()
render_bar_chart()
# # 定义一个函数来格式化百分比标签
# def autopct_format(values):
#     def my_format(pct):
#         total = sum(values)
#         val = int(round(pct*total/100.0))
#         return '{p:.2f}%'.format(p=pct, v=val)
#     return my_format
#
# # 绘制饼图
# fig1, ax1 = plt.subplots(figsize=(10, 10))
# wedges, texts, autotexts = ax1.pie(sizes, labels=labels, autopct=autopct_format(sizes),
#                                    startangle=140)


# for wedge, label in zip(wedges, labels):
#     # 获取饼状部分的角度范围和中心点
#     theta1, theta2 = np.deg2rad(wedge.theta1), np.deg2rad(wedge.theta2)
#     center = (0.5 * np.cos((theta1 + theta2) / 2) + 0.5, 0.5 * np.sin((theta1 + theta2) / 2) + 0.5)
#
#     # 读取与标签对应的图片
#     img = mpimg.imread(f'img/card/cut_{label}.jpg')  # 确保图片路径正确
#
#     # 设置图片的缩放和位置
#     zoom = 2.0 / len(sizes)  # 根据饼图的分区数量来调整缩放比例
#     imagebox = OffsetImage(img, zoom=zoom)
#     ab = AnnotationBbox(imagebox, center, frameon=False, box_alignment=(0.5, 0.5), bboxprops=dict(edgecolor='none'))
#     ax1.add_artist(ab)

    # # 获取饼状部分的起始和结束角度
    # theta1, theta2 = np.deg2rad(wedge.theta1), np.deg2rad(wedge.theta2)

    # # 计算边界框的坐标
    # r = 1.1  # 半径，稍微大于1，确保覆盖整个饼状部分
    # x1, y1 = r * np.cos(theta1), r * np.sin(theta1)
    # x2, y2 = r * np.cos(theta2), r * np.sin(theta2)
    #
    # # 创建边界框
    # bbox = Bbox.from_extents(x1, y1, x2, y2)
    #
    # # 读取与标签对应的图片
    # img_path = f'img/card/cut_{label}.jpg'  # 确保图片路径正确
    # img = plt.imread(img_path)
    #
    # # 创建并添加 BboxImage
    # bbox_image = BboxImage(bbox, norm=None, origin=None, clip_on=False)
    # bbox_image.set_data(img)
    # ax1.add_artist(bbox_image)


# # 为每个饼状部分添加图片
# for wedge, label in zip(wedges, labels):
#     # 读取与标签对应的图片
#     img = mpimg.imread(f'img/card/cut_{label}.jpg')  # 确保图片路径正确
#
#     # 设置图片的边界框
#     theta1, theta2 = np.deg2rad(wedge.theta1), np.deg2rad(wedge.theta2)
#     x, y = 0.5 * np.cos((theta1 + theta2) / 2), 0.5 * np.sin((theta1 + theta2) / 2)
#     bbox = [x-0.1, y-0.1, 0.2, 0.2]  # 根据需要调整这些值以匹配饼块的大小和位置
#
#     # 创建并添加 BboxImage
#     imagebox = OffsetImage(img, zoom=0.2)  # 调整 zoom 以匹配饼块的大小
#     ab = AnnotationBbox(imagebox, (x, y), frameon=False, box_alignment=(0.5, 0.5), bboxprops=dict(edgecolor='none'))
#     ax1.add_artist(ab)


# # 将百分比标签放在饼图外侧
# for autotext in autotexts:
#     autotext.set_color('black')
#     autotext.set_horizontalalignment('center')
#     autotext.set_size(10)
#     autotext.set_bbox(dict(facecolor='white', alpha=0.5, edgecolor='none', boxstyle='round,pad=0.5'))
#
# st.pyplot(fig1)
#
# # 使用Matplotlib创建纵向排列的柱状图
# fig, ax = plt.subplots(figsize=(10, 20))
# plt.subplots_adjust(left=0.2, right=0.8, top=0.9, bottom=0.1)
# ax.barh(list(sorted_dict.keys()),list(sorted_dict.values()))
# # ax.set_xlabel('类别')
# # ax.set_ylabel('值')
# # ax.set_title('纵向排列的柱状图示例')
# ax.xaxis.set_visible(False)
# # 隐藏所有边框
# for spine in ax.spines.values():
#     spine.set_visible(False)
#
# # 显示柱状图
# st.pyplot(fig)